import React, { useEffect, useState } from 'react';
import {Layout, Menu} from 'antd';
import MenuItem from 'antd/es/menu/MenuItem';
import icons from './iconList';
import type { MenuItemType } from 'antd/es/menu/interface';
const { Sider } = Layout;
import './index.scss'
import logo from '../../assets/logo.png'
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

interface MenuItem extends MenuItemType{
  key:string,
  label:string,
  icon?:React.ReactNode|string
  children?:MenuItem[]
}
export default function Side() {
  //将menu函数优化之后 可以直接使用redux中存入的数据
  const {menuList}=useSelector((state:any)=>state.userReducer)
  const [items, setItems] = useState<MenuItem[]>([]);
  const navigator=useNavigate()
  // 递归处理单个菜单项的图标
  function setMenuItemIcon(menuItem: MenuItem): MenuItem {
    const newItem = { ...menuItem };
    // 处理当前菜单项的图标
    if (typeof newItem.icon === 'string' && icons[newItem.icon]) {
      newItem.icon = icons[newItem.icon];
    }
    // 递归处理子菜单项
    if (newItem.children && newItem.children.length > 0) {
      newItem.children = newItem.children.map(setMenuItemIcon);
    }
    return newItem;
  }
  // 递归实现的getIcon函数，可处理任意层级的子菜单
  function getIcon(menuItems: MenuItem[]): MenuItem[] {
    return menuItems.map(setMenuItemIcon);
  }
  async function getItem():Promise<MenuItem[]>{
    const item:MenuItem[]=menuList
    //处理icon
    return getIcon(item)
  }

  useEffect(()=>{
    getItem().then((value)=>{
      if(value){
        setItems(value);
        // console.log(value);
      }else{
        console.error('No menu data available');
      }
    })
  },[])
  
  const [collapsed, setCollapsed] = useState(false);
  function handleClick(item:any){
    navigator(item.key)
  }
  return (
    <Sider 
    theme='light'
    collapsible
    collapsed={collapsed}
    onCollapse={(value) => setCollapsed(value)}
    >
    <div className="demo-logo-vertical"  style={collapsed ? {display:'none'} : undefined}>
      <img src={logo} alt="" width={18}  />
      智慧园区管理平台
    </div>
    <Menu
      defaultSelectedKeys={['/dashboard']}
      mode="inline"
      items={items!}
      onClick={handleClick}
    />
    </Sider>
  )
}
